<template>
<div class="infinite-container">
  <div class="tips-disabled center" v-if="outTime">
    您的订单已经失效！请重新预约
  </div>
  <div class="tips-warning center" v-else>
    支付剩余时间 {{m}}:{{s}}，超时自动失效
  </div>
  <mu-divider></mu-divider>
  <common-list title="挂号费用">
    <div class="confirm-money">
      ￥ {{doctor.charge}}
    </div>
  </common-list>
  <common-list title="支付方式" desc="微信支付">

  </common-list>
  <div class="login pd20">
    <mu-raised-button label="重新预约" @click="appoint" fullWidth primary class="btn-login" v-if="outTime"></mu-raised-button>
    <mu-raised-button label="立即支付" @click="pay" fullWidth primary class="btn-login" v-else></mu-raised-button>
  </div>
   <mu-dialog :open="tipsDialog" title="江苏省中医院友情提醒">
      您正在预约我院0元号，此类号源属于公益行为，不需支付。
      <div class="center login mt20">
        <mu-raised-button label="确定" @click="confirmHandle" primary class="btn-login">
        </mu-raised-button>
      </div>
    </mu-dialog>
</div>
</template>

<script>
import {leftTime} from '../../common/js/util'
import CommonList from '../../components/CommonList'
import {commonAjax, ORG_ID, PLATFORM_PREFIX, SUBMIT_SOURCE} from '../../api/api'

export default {
  data () {
    return {
      m: 0,
      s: 0,
      outTime: false,
      doctor: JSON.parse(localStorage.doctor),
      order: JSON.parse(localStorage.order),
      tipsDialog: false
    }
  },
  mounted () {
    this.$store.commit('UPDATE_TITLE', '在线支付')
    // 订单默认失效时间
    const ORDER_OUT_DATE_TIME = 0
    let _this = this
    // fix ios getTime bug .replace(/-/g, "/")
    let serviceName = ''
    if (PLATFORM_PREFIX === 'cas') {
      serviceName = 'appService'
    } else {
      serviceName = 'wechatService'
    }
    commonAjax([], `${PLATFORM_PREFIX}.${serviceName}`, 'getServerTime').then(res => {
      if (res.data.code === 200) {
        let orderCreateTime = new Date(this.order.regCloseTimeDisplay.replace(/-/g, '/'))
        let dist = new Date(res.data.body.serverTime.replace(/-/g, '/')) - new Date()
        console.log(`regCloseTimeDisplay:${orderCreateTime}`)
        let timer = setInterval(() => {
          var left = leftTime(ORDER_OUT_DATE_TIME, (dist + (new Date() - orderCreateTime)))
          if (left.m <= 0 && left.s <= 0) {
            clearInterval(timer)
            _this.outTime = true
          } else {
            _this.m = left.m
            _this.s = left.s
          }
        }, 1000)
      }
    })
    // 预结算费用
    commonAjax([this.order.regRecordId, ORG_ID, 1], `${PLATFORM_PREFIX}.registrationService`, 'preBudget').then(res => {
      if (res.data.code === 200) {
        this.doctor.charge = res.data.body.selfAmount
        if (parseInt(res.data.body.selfAmount) === 0) {
          console.log('此号为义诊号， 不需要支付')
          this.tipsDialog = true
        }
      }
    })
  },
  methods: {
    pay () {
      commonAjax([
        ORG_ID,
        this.doctor.charge,
        JSON.stringify({bustype: '11', id: this.order.regRecordId, source: SUBMIT_SOURCE}),
        this.order.regSourceId,
        localStorage.openId
      ], `${PLATFORM_PREFIX}.orderStrService`, 'orderstr').then(res => {
        console.log(res)
        this.weixinPay({
          appId: res.data.body.appId,
          timeStamp: res.data.body.timeStamp,
          nonceStr: res.data.body.nonceStr,
          package: res.data.body.package,
          signType: 'MD5',
          paySign: res.data.body.sign
        })
      }).catch(res => {
        console.warn(res)
      })
      // this.$router.push('/appointment/confirm-appoint-success')
    },
    appoint () {
      this.$router.push('/appointment/select-department')
    },
    weixinPay (data) {
      var vm = this
      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data))
          document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data))
        }
      } else {
        vm.onBridgeReady(data)
      }
    },
    onBridgeReady (data) {
      var vm = this
      window.WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          'appId': data.appId,
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign
        },
        function (res) {
          // 微信团队郑重提示：res.err_msg将在用户支付成功后返回ok
          // 但并不保证它绝对可靠。
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            vm.$router.push('/appointment/appoint-pay-success')
          } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
            vm.$store.commit('UPDATE_TOAST', {
              message: '支付失败：用户取消支付'
            })
          } else {
            alert('支付失败：' + JSON.stringify(res))
            alert('OPENID:' + localStorage.openId)
          }
        }
      )
    },
    confirmHandle () {
      this.$router.push('/appointment/appoint-pay-success')
    }
  },
  beforeDestroy () {
    this.$store.commit('UPDATE_TITLE')
  },
  components: {
    CommonList
  }
}
</script>

<style>
.paying {
  font-size:1.4em;
  text-align: center;
  padding-top: 4em;
  color: #999;
}
</style>
